<template>
  <div class="_wz_sendNoticeAdd">
    <Steps :current="current" style="width: 80%;margin: auto;">
      <Step title="基本信息"></Step>
      <Step title="机构选择"></Step>
      <Step title="信息展示"></Step>
    </Steps>
    <div style="height: 100%;overflow: auto;">
      <div v-if="current == 0" style="padding: 10px;">
        <Form ref="formAdd" :model="formData" label-position="right" :label-width="110" :rules="ruleValidate">
          <FormItem label="通知标题" prop="noticeTitle">
            <i-input v-model="formData.noticeTitle" placeholder="请填写通知标题" clearable />
          </FormItem>

          <Row>
            <Col span="8">
            <FormItem label="通知等级" prop="noticeLv">

              <i-select v-model.number="formData.noticeLv" filterable placeholder="请选择通知等级" clearable>
                <Option :value="1">普通</Option>
                <Option :value="2">重要</Option>
                <Option :value="3">紧急</Option>
              </i-select>

            </FormItem>
            </Col>
            <Col span="16">
            <FormItem label="通知人员" prop="govContact">
              <i-input v-model="formData.govContact" placeholder="请填写通知人员" clearable />
            </FormItem>
            </Col>
          </Row>


          <Row style="height: 58px;">
            <Col span="8">
            <FormItem label="文件下发" prop="noticeFileType">
              <i-switch v-model.number="formData.noticeFileType" :false-value="0" :true-value="1">
                <template #open><span>开</span></template>
                <template #close><span>关</span></template>
              </i-switch>
            </FormItem>
            </Col>
            <Col span="16" v-if="formData.noticeFileType">
            <FormItem label="通知附件" prop="multipartFile">
              <Upload name="multipartFile" :before-upload="handleUpload" action="" style="display: inline-block;">
                <Button type="primary" icon="ios-cloud-upload-outline">上传附件(仅支持mp4、docx)</Button>
                {{ fileData.name }}
              </Upload>
              <Button type="primary" icon="md-cloud-download" v-if="!!formData.noticeFileUrl && !fileData.name"
                style="margin: 0 0 0 10px;" @click="dateienHerunterladen">下载文件</Button>
            </FormItem>
            </Col>
          </Row>

          <Row>
            <Col span="8">
            <FormItem label="回复状态" prop="noticeReplyType">
              <i-switch v-model.number="formData.noticeReplyType" :false-value="0" :true-value="1">
                <template #open><span>开</span></template>
                <template #close><span>关</span></template>
              </i-switch>
            </FormItem>
            </Col>
            <Col span="16" v-if="formData.noticeReplyType">
            <FormItem label="回复时间" prop="noticeEndTime">
              <DatePicker type="datetime" v-model="formData.noticeEndTime" show-week-numbers placeholder="请选择回复时间" />
            </FormItem>
            </Col>
          </Row>
          <FormItem label="通知内容" prop="noticeContent">
            <div style="border: 1px solid #ccc;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                       :defaultConfig="{ excludeKeys: ['insertLink', 'group-image', 'fullScreen', 'group-video'] }" mode='default' />
              <Editor style="height: 500px; overflow-y: hidden;" v-model="formData.noticeContent"
                :defaultConfig="{ placeholder: '请输入内容...' }" mode='default' @onCreated="handleCreated" />
            </div>
          </FormItem>
        </Form>
      </div>
      <div v-show="current == 1" style="padding: 10px;height: 100%;" class="_wz_sendNoticeAdd_tbale">

        <!-- <Form :model="formData" label-position="right" :label-width="120">
          <FormItem label="运输类型" class="ivu-form-item-required">
            <CheckboxGroup v-model="formData.noticePublishValueCode">
              <Checkbox v-for="item in transportTypeList" :label="item.code" :key="item.code">{{ item.value }}</Checkbox>
            </CheckboxGroup>
          </FormItem>
        </Form> -->
        <div style="height: 100%;overflow: auto;">
          <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
        </div>
      </div>

      <div v-show="current == 2"  style="padding: 10px;height: 100%;">
        <tableDataShow :tableDataProp="formData" />
        <!-- <div class="innerBody">
          <div class="row">
            <span class="tit">通知标题：</span>
            <span class="data">{{ formData.noticeTitle }}</span>
          </div>

          <div class="row">
            <div class="col">
              <span class="tit">通知等级：</span>
              <span class="data" v-if="formData.noticeLv == 1">普通</span>
              <span class="data" v-if="formData.noticeLv == 2">重要</span>
              <span class="data" v-if="formData.noticeLv == 3" style="color: red;">紧急</span>
            </div>
            <div class="col" style="margin-left: 180px;">
              <span class="tit">通知人员：</span>
              <span class="data">{{ formData.govContact }}</span>
            </div>

          </div>

          <div class="row">
            <span class="tit">文件状态：</span>
            <span class="data">{{ formData.noticeReplyType == 1 ? '存在' : '不存在' }}</span>
          </div>

          <div class="row">
            <span class="tit">回复时间：</span>
            <span class="data">{{ common.timeFormatting(new Date(formData.noticeEndTime), 'yyyy-MM-dd hh:mm:ss') }}</span>
          </div>

          <div class="row">
            <span class="tit"> 机构列表：</span>

          </div>


        </div> -->



        <div class="ul">
          <!-- <wzTbale  :tableData="tableData"></wzTbale> -->
          <Table :columns="tableData.columnsSee" :data="TableData" ></Table>
        </div>
      </div>
    </div>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" type="primary" @click="addSubmit" v-if="current == 2">提交</Button>
      <Button style="margin-right: 8px" type="primary" v-if="current != 0" @click="Previous()">上一步</Button>
      <Button style="margin-right: 8px" type="primary" v-if="current != 2" @click="nextFun()">下一步</Button>
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>

    </div>
  </div>
</template>
<script>


import { shallowRef, getCurrentInstance, inject, nextTick, reactive, toRefs, toRef, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, ref, defineComponent, toRaw, watch } from 'vue'
import { useRouter, useRoute } from "vue-router";

import { useMainStore } from '../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex
import common from "../../api/common"

import wzTbale from "../../components/table/index.vue";
import tableDataShow from "./tableDataShow.vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { systemDictList } from "@/util/commonInterfaces";

//reactive
export default defineComponent({
  name: 'sendNoticeAdd',//组件名称
  components: {
    Editor, Toolbar,
    wzTbale,tableDataShow
  },//组件引用
  props: ['selectData'],//接收来自父组件的数据
  setup(props, context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $common = inject('$common');//自己封装的方法


    // 用于获取$refs
    const formAdd = ref();
    let wzTbale = ref();
    const TableData = ref();

    const state = reactive({
      transportTypeList: [],//运输类型
      current: 0,//当前状态
      formData: {
        noticeFileType: 1,
        noticeReplyType: 1,
        noticeEndTime: new Date(),
        noticeTitle:"",
        noticeLv:"",
        orgContact:"",

      },//表单数据
      ruleValidate: {//表单正则
        noticeTitle: [
          { required: true, message: "请填写通知标题", trigger: "blur" }
        ],
        noticeLv: [
          { type: 'number', required: true, message: "请选择通知等级", trigger: "blur" }
        ],
        orgContact: [
          { required: true, message: "请填写通知人员", trigger: "blur" }
        ],
        noticeEndTime: [
          { type: 'date', required: true, message: "请选择回复时间", trigger: "blur" }
        ],
      },
      fileData: {
        data: null,
        name: '',
      },

      tableData: {
        height: "100%", //表格高度 auto
        page: false, //分页是否使用
        columns: [
          //表头数据
          { type: "selection", width: 70, align: "center" },
          { type: "index", width: 70, align: "center", title: "序号" },
          { title: '机构名称', minWidth: 210, key: 'deptName', tooltip: true, resizable: true, },
          // {title: '机构类型', minWidth: 120, key: 'transportValue',tooltip:true,resizable: true,},
          // {title: '法人代表', minWidth: 120, key: 'legalPerson',tooltip:true,resizable: true,},
          // {title: '经营负责人', minWidth: 120, key: 'personCharge',tooltip:true,resizable: true,},
          // {title: '负责人电话', minWidth: 120, key: 'personChargePhone',tooltip:true,resizable: true,},
          // {title: '营业执照号', minWidth: 180, key: 'uniformSocialCreditCode',tooltip:true,resizable: true,},
        ],
        columnsSee: [
          //表头数据
          // { type: "selection", width: 70, align: "center" },
          // { type: "index", width: 70, align: "center", title: "序号" },
          { title: '机构名称', minWidth: 210, key: 'deptName', tooltip: true, resizable: true, },
          // {title: '机构类型', minWidth: 120, key: 'transportValue',tooltip:true,resizable: true,},
          // {title: '法人代表', minWidth: 120, key: 'legalPerson',tooltip:true,resizable: true,},
          // {title: '经营负责人', minWidth: 120, key: 'personCharge',tooltip:true,resizable: true,},
          // {title: '负责人电话', minWidth: 120, key: 'personChargePhone',tooltip:true,resizable: true,},
          // {title: '营业执照号', minWidth: 180, key: 'uniformSocialCreditCode',tooltip:true,resizable: true,},
        ],
        dataList: []
      }
    });

    //监听

    //监听

    // watch(() => state.formData.noticePublishValueCode, (news, old) => {
    //   if (state.formData.noticePublishValueCode.length > 0) {
    //     studentTypeFun();
    //   } else {
    //     state.tableData.dataList = [];
    //     $ViewUIPlus.Message.error('请至少选择一个运输类型');
    //   }
    // }, { deep: true });




    //编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    // 记录 editor 实例，重要！
    const handleCreated = (editor) => {
      editorRef.value = editor
    }




    //文件上传
    const handleUpload = (file) => {
      let type = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (type == "MP4" || type == "mp4") {//视频
        state.formData.noticeFileType = 1;
        state.fileData.data = file;
        state.fileData.name = file.name;
      } else if (type == "DOCX" || type == "docx") {//word
        state.formData.noticeFileType = 2;
        state.fileData.data = file;
        state.fileData.name = file.name;
      } else {
        $ViewUIPlus.Message.error('您上传的文件类型不匹配');
        return false;
      }
      return false;
    }


    //上一步
    const Previous = () => {
      if (state.current == 0) {
        return false;
      } else if (state.current == 1) {
        state.current = 0;
      } else {
        state.current = 1;
      }
    }

    //下一步
    const nextFun = () => {
      if (state.current == 0) {
        formAdd.value.validate(async (valid) => {
          if (valid) {
            state.current = 1;
            studentTypeFun();
          } else {
            $ViewUIPlus.Message.error('请正确填写表单');
          }
        })
      } else if (state.current == 1) {
        TableData.value = wzTbale.value.tableDataSelected()
        console.log(wzTbale.value)

        // let tableDataList = wzTbale.value.tableDataSelected();
        // if (tableDataList.length == 0) {
        //   $ViewUIPlus.Message.error('请至少选择一个机构');
        //   return false;
        // }

        state.current = 2;
      }

    }

    //提交
    const addSubmit = () => {


      let data = JSON.parse(JSON.stringify(state.formData));
      console.log(data)

      let formData = new FormData();

      // 运输类型 中文处理
      // let noticePublishValueName = [];
      // if (data.noticePublishValueCode && data.noticePublishValueCode.length > 0) {
      //   state.transportTypeList.forEach(item => {
      //     if (data.noticePublishValueCode.indexOf(item.code) > -1) {
      //       noticePublishValueName.push(item.value)
      //     }
      //   })
      // }
      // data.noticePublishValueName = noticePublishValueName;

      // //运输类型 逗号分隔
      // data.noticePublishValueCode = data.noticePublishValueCode.join();
      // data.noticePublishValueName = data.noticePublishValueName.join();
        console.log(wzTbale)
      //处理表格 数据
      let tableDataList = wzTbale.value.tableDataSelected();
      if (tableDataList.length == 0) {
        $ViewUIPlus.Message.error('请至少选择一个机构');
        return false;
      }

      let noticePublishDeptValue = [];
      tableDataList.map((k, i) => {
        noticePublishDeptValue.push(k.uuid)
      })
      data.noticePublishDeptValue = noticePublishDeptValue.join();


      //处理 回复时间
      if (!data.noticeReplyType) {
        delete data.noticeEndTime;
      } else {
        //时间处理转换
        data.noticeEndTime = $common.timeFormatting(new Date(data.noticeEndTime), 'yyyy-MM-dd hh:mm:ss')
      }

      //处理文件
      if (!!data.noticeFileType && state.fileData.data) {
        formData.append("multipartFile", state.fileData.data);
      }


      data.noticeFileTypeSwitch = !!data.noticeFileType
      data.noticeReplyTypeSwitch = !!data.noticeReplyType



      for (let key in data) {
        formData.append(key, data[key]);
      }




      $axios.post(apiUrl.noticeGovMessageNoticeGovMessageSaveOrUpdate, formData).then((res) => {
        if (res.data.code == 0) {
          $ViewUIPlus.Message.success('保存成功');
          context.emit('closeFun', true)
        } else {
          $ViewUIPlus.Message.error('保存失败');
        }
      }).catch((err) => {
        console.log("失败", err)
      })



    }
    //to  do  解决企业下拉框的bug

    //类型发生变化  加载表格数据
    const studentTypeFun = () => {
      $axios.post(apiUrl.coreDeptCoreDeptList, { typeCode: '1104' }).then((res) => {
        if (!!props.selectData.id) {//修改
          if (!!state.formData.noticePublishDeptValue) {

            res.data.data.forEach(function (k, i) {
              console.log(k,i)
              console.log(state.formData)
              state.formData.noticePublishDeptValue = state.formData.noticePublishDeptValue.split(",")
              state.formData.noticePublishDeptValue.forEach(function (ko, io) {
                if (k.uuid == ko) {
                  k._checked = true;
                }
              });
            });
          }
        }
        state.tableData.dataList = res.data.data;
      }).catch((err) => {
        console.log("失败", err)
      })

    }

    //下载文件
    const dateienHerunterladen = () => {
      window.open(apiUrl.export + state.formData.noticeFileUrl)
    }


    // 其他的生命周期
    onBeforeMount(() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted(async () => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")

      state.transportTypeList = await systemDictList({ type: 'transport_type' })

      props.selectData.noticeEndTime = common.timeFormatting(props.selectData.noticeEndTime,'yyyy-MM-dd hh:mm:ss')



      if (!!props.selectData.id) {//修改
        state.formData  = props.selectData
        $axios.post(apiUrl.noticeGovMessageNoticeGovMessageRecordPageList, { noticeUuid: props.selectData.uuid }).then((res) => {
          let formData = res.data.data;
          // state.formData = formData;
          // console.log(state.formData)
        }).catch((err) => {
          console.log("失败", err)
        })
      } else {//添加
      let noticePublishValueCode = [];
      state.transportTypeList.map((k, i) => {
        noticePublishValueCode.push(k.code)
      })
      state.formData.noticePublishValueCode = noticePublishValueCode;
      }


    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate(() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated(() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount(() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted(() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      handleUpload,//通知附件
      Previous,//上一步
      nextFun,//下一步
      addSubmit,//提交
      formAdd,//用于表单验证使用
      studentTypeFun,//类型发生变化  加载表格数据
      dateienHerunterladen,//下载文件
      common,
      wzTbale,//表格 调用
      editorRef,//编辑器实例，必须用 shallowRef
      handleCreated,//记录 editor 实例，重要！
      TableData

    }
  }
})


</script>
<style lang="less">
._wz_sendNoticeAdd {
  height: 100%;
  display: flex;
  flex-direction: column;

  ._wz_sendNoticeAdd_tbale {

    height: 100%;
    display: flex;
    flex-direction: column;
  }
}
</style>
